import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {PageContainer, ProTable} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Popconfirm} from 'antd';
import React, {useRef, useState} from 'react';
import type {SortOrder} from 'antd/es/table/interface';
import {
  addCategoryUsingPost,
  deleteCategoryUsingPost,
  listCategoryVoByPageUsingPost,
  updateCategoryUsingPost
} from "@/services/backend/categoryController";
import UpdateModal from "@/pages/Admin/CategoryManage/components/UpdateModal";
import CreateModal from "@/pages/Admin/CategoryManage/components/CreateModal";


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.CategoryVO>();
  const [openConfirm, setOpenConfirm] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.CategoryVO) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改中');
    try {
      const res = await updateCategoryUsingPost({
        id: currentRow.id,
        ...fields,
      });
      hide();
      if (res.code === 0)
        message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('操作失败' + error.message);
      return false;
    }
  };

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.CategoryAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addCategoryUsingPost({
        ...fields,
      });
      hide();
      if (res.code === 0)
        message.success('创建成功');
      handleModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败，' + error.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param record
   */
  const handleRemove = async (record: API.CategoryVO) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      const res = await deleteCategoryUsingPost({
        id: record.id,
      });
      hide();
      if (res.code === 0)
        message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };



  const columns: ProColumns<API.CategoryVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      width: 50,
    },
    {
      title: '分类',
      dataIndex: 'name',
      valueType: 'text',
      width: 120,
    },
    {
      title: '图书总量',
      dataIndex: 'nowNumber',
      // valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => (
        <>{record.nowNumber ? record.nowNumber : 0}</>
      ),
      width: 50,
      // sorter: true,
    },
    {
      title: '现借阅量',
      dataIndex: 'borrowNumber',
      // valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => (
        <>{record.borrowNumber ? record.borrowNumber : 0}</>
      ),
      width: 50,
      // sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button
          size={'small'}
          type={'text'}
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        <Popconfirm
          key="borrow"
          title="你确认删除吗"
          disabled={openConfirm}
          onConfirm={() => {
            handleRemove(record);
            setOpenConfirm(false)
          }}
          onCancel={() => {
            setOpenConfirm(false)
          }}
        >
          <Button type={'text'}
                  size={'small'}
                  danger
                  key="removeBtn"
                  onClick={() => {
                    setOpenConfirm(true)
                  }}
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        pagination={{
          pageSize: 10,
        }}
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey={currentRow?.id?.toString() || undefined}
        search={{
          labelWidth: 120,
        }}
        // dataSource={categoryList}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        // @ts-ignore
        request={async (
          params: {
            pageSize?: number | undefined;
            current?: number | undefined;
            keyword?: string | undefined;
          },
          sort: Record<string, SortOrder>,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          let sortFieldStr = "";
          let sortOrderStr: any;
          if (Object.keys(sort).length > 0) {
            const [firstSort] = Object.entries(sort); // 获取sort对象的第一个键值对
            sortFieldStr = firstSort[0];
            sortOrderStr = firstSort[1];
          }
          const res = await listCategoryVoByPageUsingPost({
            ...params,
            sortField: sortFieldStr,
            sortOrder: sortOrderStr,
          });
          if (res?.data) {
            return {
              data: res?.data.list || [],
              success: true,
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        // @ts-ignore
        columns={columns}
      />
      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            // console.log(currentRow)
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          /*if (!showDetail) {
            setCurrentRow(undefined);
          }*/
        }}
        visible={updateModalVisible}
        values={currentRow || {}}
      />
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalVisible(false);
        }}
        // @ts-ignore
        onSubmit={(values) => {
          // @ts-ignore
          handleAdd(values);
        }}
        visible={createModalVisible}
      />
    </PageContainer>
  );
};
export default TableList;
